package com.zmm.type.service.impl;

import com.zmm.common.base.model.ResultCode;
import com.zmm.common.constant.NumberConstant;
import com.zmm.common.enums.StatusEnums;
import com.zmm.common.exception.handle.BusinessException;
import com.zmm.type.custom.method.util.CateUtil;
import com.zmm.type.dao.CategoryDao;
import com.zmm.type.model.Category;
import com.zmm.type.service.CategoryService;
import com.zmm.type.vo.CategoryTreeNode;
import com.zmm.type.vo.CategoryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Name CategoryServiceImpl
 * @Author Zebulon
 * @Date By 2021-06-27 18:56:49
 */
@Slf4j
@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryDao categoryDao;

    @CacheEvict(value = "category")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer addCategory(Category category) {
        category.setCreateTime(System.currentTimeMillis());
        // 可能需要更新缓存 --> SpringCache
        return categoryDao.insertCategory(category);
    }

    @CacheEvict(value = "category")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void modifyCategory(Category category) throws BusinessException {
        if (category == null) {
            throw new BusinessException("参数不能为空");
        }
        if (category.getCategoryId() == 0) {
            throw new BusinessException("类目id不能为空");
        }

        Integer result = categoryDao.updateCategory(category);
        if (result <= 0) {
            throw new BusinessException("更新类目失败");
        }
        //类目修改成功修改下面所有子类引用的类目名称 
        try {
            updateSubCateName(category);
            
            // 后台的三级类目要修改关联的规格 --> 先删除类目和规格的关联
            /**
             * 
            if (category.getFirstCategoryId() != 0 && category.getSecondCategoryId() != 0
                    && CategoryEnum.BACK_STAGE_CATE.getCode().equals(category.getCategoryType())) {
                //先删除类目和规格的关联
                categorySpecDao.delCateSpec(category.getCategoryId())
                if (StringUtil.isNotBlank(specIds)) {
                    addCateSpec(category, specIds)
                }
            }
             */
        } catch (Exception e) {
            log.error("category-editCategoryAndSpec error:{},{},{}", category.getCategoryId(), category.getCategoryName(), e);
            throw new BusinessException("update category or categorySpec is fail", e);
        }
    }

    @CacheEvict(value = "category")
    @Override
    public Integer removeCategory(Integer categoryId) {
        Integer result = ResultCode.NULL_PARAMETER.getCode();
        if (categoryId == null) {
            return result;
        }
        Category cate = categoryDao.findCategoryById(categoryId);
        if (cate == null) {
            return result;
        }

        try {
            // 如果是一级类目，看下面是否有二级类目，有则不可以删除
            if (cate.getFirstCategoryId() == 0) {
                // 一级类目下 ->如果有二级类目不可以删除
                Integer secondCateCount = categoryDao.selectCategoryByFirstId(cate);
                if (secondCateCount > 0) {
                    return result;
                }
            } else {
                // 如果是二级类目，看下面是否有三级类目，有不可删除
                if (cate.getSecondCategoryId() == 0) {
                    List<Category> threeCateCount = categoryDao.selectCategoryBySecondId(cate);
                    if (threeCateCount != null && threeCateCount.size() > 0) {
                        return result;
                    }
                } else {
                    //后台三级类目，看下面是否有商品
                    Integer goodsNum = NumberConstant.ZERO ;
                    if (NumberConstant.TWO.equals(cate.getCategoryType())) {
                        // 查询 商品表 -- good
                        // goodsNum = categoryDao.selectGoodsNumByCategoryId(categoryId)
                    } else {
                        // 前台三级类目下是否有商品 -- category_front
                        // goodsNum = categoryDao.selectFrontGoodsNumByCategoryId(categoryId)
                    }
                    if (goodsNum > 0) {
                        return result;
                    }
                }
            }
        }catch (Exception e) {
            log.error("category-delCategory error:{}", cate.getCategoryId());
        }
        return result;
    }

    /**
     * 类目修改成功修改下面所有子类引用的类目名称 
     * @author: 900045
     * @date: 2021-07-05 16:25:41
     * @throws 
     * @param category: 
     * @return: void
     **/
    private void updateSubCateName(Category category) {
        // 一级修改所有firstCategoryId
        if (category.getFirstCategoryId() == 0) {
            categoryDao.updateSubCateNameForFirst(category);
        } else if (category.getFirstCategoryId() != 0 && category.getSecondCategoryId() == 0){
            // 二级修改所有secondCategoryId
            categoryDao.updateSubCateNameForSecond(category);
        }
    }

    @Override
    public Category queryCategoryById(Integer categoryId) {
        return categoryDao.findCategoryById(categoryId);
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public List<CategoryVo> queryAllCategory(Integer categoryType) {
        log.debug("[CategoryServiceImpl]中的[queryAllCategory]方法被调用.....");
        return findAllCategory(categoryType);
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public List<CategoryTreeNode> findCategoryTree(Integer categoryType) {
        List<CategoryTreeNode> cateList = categoryTreeHandler(categoryType);
        return cateList;
    }


    @Override
    public List<Category> findThreeCategoryBySecondCategoryId(Category category) {
        if (ObjectUtils.isEmpty(category)) {
            return null;
        }
        return categoryDao.selectThreeCategoryBySecondCategoryId(category);
    }

    private List<CategoryTreeNode> categoryTreeHandler(Integer categoryType) {
        if (categoryType == 0) {
            return null;
        }
        //查询所有类目
        List<Category> cateList = categoryDao.selectAllCategoryByCategoryType(categoryType);
        if (cateList == null || cateList.size() == 0) {
            return null;
        }
        List<CategoryTreeNode> treeList = CateUtil.getTreeNodes(cateList);
        return treeList;
    }

    @Override
    public Category findCategoryByParentId(Integer categoryId) {
        return categoryDao.selectCategoryByParentId(categoryId);
    }

    @Override
    public boolean isExistName(Category category) {
        Integer result = categoryDao.isExistName(category);
        if (result > 0){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查询全部的类目
     * @author: 900045
     * @date: 2021-07-05 15:31:14
     * @throws 
     * @param categoryType: 
     * @return: java.util.List<com.zmm.type.vo.CategoryVo>
     **/
    private List<CategoryVo> findAllCategory(Integer categoryType){
        List<Category> categoryList = categoryDao.findAllCategory(categoryType, StatusEnums.NORMAL.getCode(), StatusEnums.SHOW.getCode());
        
        if (CollectionUtils.isEmpty(categoryList)) {
            return null;
        }
        
        //格式转换 //一级类目 MAP
        Map<Integer, CategoryVo> firstMap = new HashMap<>();

        //三级类目列表
        List<CategoryVo> firstList = new ArrayList<>();

        //三级类目列表
        List<CategoryVo> subList = new ArrayList<>();

        CategoryVo vo = null;
        for (Category category:categoryList) {
            if (category.getFirstCategoryId() != 0 && category.getSecondCategoryId() == 0) {
                //当前版本不要二级类目
                continue;
            }
            vo = new CategoryVo();
            vo.setCategoryId(category.getCategoryId());
            vo.setCategoryName(category.getCategoryName());
            vo.setSort(category.getSort());
            vo.setParentId(category.getFirstCategoryId());
            //一级
            if (category.getFirstCategoryId() == 0) {
                firstMap.put(category.getCategoryId(), vo);
                firstList.add(vo);
            } else {
                // 查询 图片集合 获取 地址
                //vo.setImgSrc(fileDao.selectByFileId((cate.getCategoryImgId())).getFileUrl())
                subList.add(vo);
            }
        }

        for (CategoryVo categoryVo : subList) {
            vo = firstMap.get(categoryVo.getParentId());
            if (vo == null) {
                continue;
            }
            if (vo.getChildList() == null) {
                vo.setChildList(new ArrayList<>());
            }
            vo.getChildList().add(categoryVo);
        }
        return firstList;
    }
}
